// controllers/userController.js
const db = require('../config/db');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const secretKey = 'my_secret_key';

function MD5(password) {
    return crypto.createHash('md5').update(password).digest('hex');
}

exports.getUser = (req, res) => {
    db.query('SELECT id,logintime,loginip,name, username,phone, role FROM os_users', (err, results) => {
        if (err) {
            res.status(500).json({ message: '从数据库获取数据时出错' });
            return;
        }
        res.json(results);
    });
};

exports.searchUser = (req, res) => {
    const keyword = req.query.keyword;
    const query = `
        SELECT * FROM os_users 
        WHERE username LIKE ? 
        OR name LIKE ? 
        OR phone LIKE ?`;
    const searchKeyword = `%${keyword}%`;
    if (req.query.keyword === '') {
        res.status(400).json({ message: '请输入搜索关键字' });
    } else {
        db.query(query, [searchKeyword, searchKeyword, searchKeyword], (error, results) => {
            if (error) {
                res.status(500).json({ error: 'Error' });
                return;
            }
            res.json(results);
        });
    }
};

exports.addUser = (req, res) => {
    const { name, username, password, phone, role } = req.body;
    const authHeader = req.headers.authorization;
    let userRole = 'user'; // 默认为普通用户角色
    if (authHeader) {
        const token = authHeader.split(' ')[1];
        const decoded = jwt.verify(token, secretKey);
            // console.log(decoded);
            if (decoded.role === 'admin') {
                userRole = role || 'user';
            }
    }
    const sqlInsert = 'INSERT INTO os_users (name, username, password, phone, role) VALUES (?, ?, MD5(?), ?, ?)';
    db.query(sqlInsert, [name, username, password, phone, userRole], (err, results) => {
        if (err) {
            res.status(500).json({ message: '插入数据库失败'});
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '添加成功' });
        } else {
            res.status(400).json({ message: '添加失败' });
        }
    });
};

exports.updateUser = (req, res) => {
    const { id } = req.params;
    const { name,username, password,phone, role } = req.body;
    const sql = 'UPDATE os_users SET name = ?, username = ?, password = MD5(?),phone = ?, role = ? WHERE id = ?';
    db.query(sql, [name, username, password, phone, role, id], (err, results) => {
        if (err) {
            res.status(500).json({ message: '插入数据库失败'});
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '修改成功' });
        } else {
            res.status(400).json({ message: '修改失败' });
        }
    });
};

exports.deleteUser = (req, res) => {
    const { id } = req.params;
    const sqlDelete = 'DELETE FROM os_users WHERE id = ?';
    db.query(sqlDelete, [id], (err, results) => {
        if (err) {
            res.status(500).send('删除数据库失败');
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '删除成功' });
        } else {
            res.status(404).json({ message: '未找到数据', id: id });
        }
    });
};

exports.userNum = (req, res) => {
    db.query('SELECT COUNT(*) AS total FROM os_users', (err, results) => {
        if (err) {
            res.status(500).json({ error: '查询数据库失败' });
            return;
        }
        const total = results[0].total;
        res.json({ total });
    });
};

exports.loginTime = (req, res) => {
    const { logintime, userip, username } = req.body;
    db.query('UPDATE os_users SET logintime = ?, loginip = ? WHERE username = ?',
        [logintime, userip, username], (err, results) => {
            if (err) {
                res.status(500).send('插入数据库失败');
                return;
            }
            if (results.affectedRows > 0) {
                res.status(200).json('插入成功');
            } else {
                res.status(404).json('插入失败');
            }
        });
};

exports.loginIp = (req, res) => {
    const loginip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    res.json({ loginip });
};